// pages/order-confirm/order-confirm.js
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';

import {
  apiSubmitOrder
} from '../../service/api/order';

let restCardList = [];

Page({

  data: {
    orderList: [],
    totalPrice: 0,
    userInfo: {}
  },

  // 添加地址
  chooseAddress() {
    wx.navigateTo({
      url: '../address/address?type=add',
    })
  },

  changeUserInfo(userInfo) {
    this.setData({
      userInfo
    })
  },

  // 提交订单
  onSubmit() {
    Dialog.confirm({
        title: '确定提交订单',
      })
      .then(() => {
        Toast('提交订单进行支付');
        const {
          userInfo: {
            address,
            name,
            phone
          },
          orderList
        } = this.data;
        const product_list = [];
        orderList.forEach(item => {
          product_list.push(item.id)
        })
        apiSubmitOrder({
          product_list,
          address,
          phone,
          name,
        }).then(res => {
          if (res?.data?.res) {
            setTimeout(() => {
              wx.switchTab({
                url: '../index/index',
              })
              wx.setStorageSync('card-data', restCardList)
            }, 1000)
          }
        })
      })
      .catch(() => {
        // on cancel
      });
  },

  handleProductData() {
    const cardList = wx.getStorageSync('card-data')
    const activedItems = [];
    let totalPrice = 0;
    cardList.forEach(item => {
      if (item.actived) {
        activedItems.push(item)
        totalPrice += Number(item.price) * Number(item.num)
      } else {
        restCardList.push(item)
      }
    })
    this.setData({
      orderList: activedItems,
      totalPrice
    })
  },

  handleUserInfo(options) {
    if (options.address) {
      this.setData({
        userInfo: options
      })
    }
  },

  onLoad(options) {
    this.handleProductData()
    this.handleUserInfo(options)
  }
})